import { useEffect, useRef, useState } from 'react';
import React from 'react'
import { SearchOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { Button, Form, Input, Popconfirm, Table, Modal,message,Space } from 'antd';
import { getAllArticles, delArticle } from '../api/article'
const Article = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  useEffect(() => {
    getAllArticles().then(res => {
      setDataSource(res.data)
    })
  }, [])
  // MODAL
  const [modalTitle, setModalTitle] = useState('')
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const handleSearch = (selectedKeys, confirm, dataIndex) => {
      confirm();
      setSearchText(selectedKeys[0]);
      setSearchedColumn(dataIndex);
  };
  const handleReset = (clearFilters) => {
      clearFilters();
      setSearchText('');
  };
  const getColumnSearchProps = (dataIndex) => ({
      filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
          <div
              style={{
                  padding: 8,
              }}
              onKeyDown={(e) => e.stopPropagation()}
          >
              <Input
                  ref={searchInput}
                  placeholder={`Search ${dataIndex}`}
                  value={selectedKeys[0]}
                  onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                  onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
                  style={{
                      marginBottom: 8,
                      display: 'block',
                  }}
              />
              <Space>
                  <Button
                      type="primary"
                      onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
                      icon={<SearchOutlined />}
                      size="small"
                      style={{
                          width: 90,
                      }}
                  >
                      搜索
                  </Button>
                  <Button
                      onClick={() => clearFilters && handleReset(clearFilters)}
                      size="small"
                      style={{
                          width: 90,
                      }}
                  >
                      重置
                  </Button>
                  <Button
                      type="link"
                      size="small"
                      onClick={() => {
                          confirm({
                              closeDropdown: false,
                          });
                          setSearchText(selectedKeys[0]);
                          setSearchedColumn(dataIndex);
                      }}
                  >
                      过滤
                  </Button>
                  <Button
                      type="link"
                      size="small"
                      onClick={() => {
                          close();
                      }}
                  >
                      关闭
                  </Button>
              </Space>
          </div>
      ),
      filterIcon: (filtered) => (
          <SearchOutlined
              style={{
                  color: filtered ? '#1677ff' : undefined,
              }}
          />
      ),
      onFilter: (value, record) =>
          record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
      onFilterDropdownOpenChange: (visible) => {
          if (visible) {
              setTimeout(() => searchInput.current?.select(), 100);
          }
      },
      render: (text) =>
          searchedColumn === dataIndex ? (
              <Highlighter
                  highlightStyle={{
                      backgroundColor: '#ffc069',
                      padding: 0,
                  }}
                  searchWords={[searchText]}
                  autoEscape
                  textToHighlight={text ? text.toString() : ''}
              />
          ) : (
              text
          ),
  });
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // TABLE
  const [dataSource, setDataSource] = useState([]);
  const [count, setCount] = useState(2);
  const handleDelete = (id) => {
    delArticle({id}).then(res => {
      if (res.status == 200) {
        messageApi.open({
          type: 'success',
          content: '删除成功！',
          duration: 3,
        });
        getAllArticles().then(res => {
          setDataSource(res.data)
        })
      } else {
        messageApi.open({
          type: 'warning',
          content: res.message,
          duration: 3,
        });
      }
    })
  };
  const handleDetail = (id) => {
    const path = `/articleDetail/${id}`;

    navigate(path)
  }
  const defaultColumns = [
    {
      title: '标题',
      dataIndex: 'title',
      ...getColumnSearchProps('title'),
      render: (_, record) =>
        dataSource.length >= 1 ? (

          <div style={{ display: 'flex' }}>
            <a onClick={() => handleDetail(record.id)}>{record.title}</a>
          </div>

        ) : null,
    },
    {
      title: '分类',
      dataIndex: 'category',
      ...getColumnSearchProps('category'),
    },
    {
      title: '作者',
      dataIndex: 'author',
      ...getColumnSearchProps('author'),
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) =>
        dataSource.length >= 1 ? (
          <div style={{ display: 'flex', justifyContent: 'space-around' }}>
            <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.id)}>
              <a>删除</a>
            </Popconfirm>

            <a onClick={() => handleEdit(record.id)}>编辑</a>
          </div>
        ) : null,
    },
  ];


  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,

        title: col.title,

      }),
    };
  });

  const handleEdit = (id) => {
    const path = `/articleWrite/${id}`;

    navigate(path)

  }
  return <div>
    {contextHolder}
    <Table
      rowKey={record => record.id}
      bordered
      dataSource={dataSource}
      columns={columns}
    />

  </div>
}

export default Article